# -*- coding: utf-8 -*-
# @Time: 2023/4/17 22:56
# @File: 视频编辑.py
import os
import json
import subprocess


FFMPEG = r"C:\Program Files (x86)\ffmpeg\bin\ffmpeg.exe"
FFPROBE = r"C:\Program Files (x86)\ffmpeg\bin\ffprobe.exe"


def get_duration(file):
    cmd = f'"{FFPROBE}" -v quiet -print_format json -show_format "{file}"'
    byte_data = subprocess.Popen(
        cmd, shell=False, stdout=subprocess.PIPE).stdout.readlines()
    json_data = json.loads("".join(
        [bytes.decode(i.strip()) for i in byte_data]))
    return float(json_data["format"]["duration"])


def cut_tail(input_file, output_file=None, cut_time=0):
    if output_file is None:
        # 输出文件名称为输入文件名称追加output后缀名
        dot = input_file[::-1].index(".") + 1
        output_file = input_file[:-dot] + "_output" + input_file[-dot:]
    duration = get_duration(input_file)
    new_duration = duration - cut_time
    cmd = f'"{FFMPEG}" -ss 0 -t {new_duration} -accurate_seek -i "{input_file}"' \
          f' -codec copy -avoid_negative_ts 1 "{output_file}"'
    subprocess.Popen(cmd)


def cut_header(input_file, output_file=None, cut_time=0):
    if output_file is None:
        # 输出文件名称为输入文件名称追加output后缀名
        dot = input_file[::-1].index(".") + 1
        output_file = input_file[:-dot] + "_output" + input_file[-dot:]
    cmd = f'"{FFMPEG}" -ss {cut_time} -accurate_seek -i "{input_file}"' \
          f' -codec copy -avoid_negative_ts 1 "{output_file}"'
    subprocess.Popen(cmd)


def folder_cut(folder, cut_function, cut_time=0):
    parent_folder, folder_name = os.path.split(folder)
    new_folder = os.path.join(parent_folder, folder_name + "_output")
    if not os.path.exists(new_folder):
        os.mkdir(new_folder)
    for file_name in os.listdir(folder):
        input_file = os.path.join(folder, file_name)
        output_file = os.path.join(new_folder, file_name)
        cut_function(input_file, output_file, cut_time)
        print("剪切完了:", file_name)


def rename_number(folder):
    for index, file_name in enumerate(os.listdir(folder)):
        old_name = os.path.join(folder, file_name)
        new_name = os.path.join(folder, str(index).zfill(3) + file_name)
        os.rename(old_name, new_name)


def main():
    pass


if __name__ == "__main__":
    main()
